<?php

namespace app\model\oa;

use app\model\BaseModel;

/**
 * 工作报告模型
 * 对应数据表：oa_work_report
 */
class WorkReport extends BaseModel
{
    /**
     * 数据表名
     * @var string
     */
    protected $name = 'work_report';

    /**
     * 主键名
     * @var string
     */
    protected $pk = 'id';

    /**
     * 字段类型转换
     * @var array
     */
    protected $type = [
        'id' => 'integer',
        'admin_id' => 'integer',
        'report_type' => 'integer',
        'report_date' => 'integer',
        'title' => 'string',
        'content' => 'string',
        'summary' => 'string',
        'plan' => 'string',
        'status' => 'integer',
        'approver_id' => 'integer',
        'approve_time' => 'integer',
        'approve_remark' => 'string',
        'create_time' => 'integer',
        'update_time' => 'integer',
    ];

    /**
     * 可搜索字段
     * @var array
     */
    protected $searchField = ['title', 'content', 'summary', 'plan'];

    /**
     * 报告类型
     * @var array
     */
    public const REPORT_TYPE = [
        1 => '日报',
        2 => '周报',
        3 => '月报',
        4 => '季度报',
        5 => '年报',
    ];

    /**
     * 报告状态
     * @var array
     */
    public const STATUS = [
        1 => '草稿',
        2 => '待审核',
        3 => '已通过',
        4 => '已拒绝',
    ];

    /**
     * 关联提交人
     * @return \think\model\relation\BelongsTo
     */
    public function admin()
    {
        return $this->belongsTo('app\model\admin\User', 'admin_id', 'id');
    }

    /**
     * 关联审核人
     * @return \think\model\relation\BelongsTo
     */
    public function approver()
    {
        return $this->belongsTo('app\model\admin\User', 'approver_id', 'id');
    }

    /**
     * 获取工作报告列表
     * @param array $params 查询参数
     * @return \think\Paginator
     */
    public function getReportList($params = [])
    {
        $where = [];
        
        if (!empty($params['admin_id'])) {
            $where[] = ['admin_id', '=', $params['admin_id']];
        }
        
        if (!empty($params['report_type'])) {
            $where[] = ['report_type', '=', $params['report_type']];
        }
        
        if (isset($params['status']) && $params['status'] !== '') {
            $where[] = ['status', '=', $params['status']];
        }
        
        if (!empty($params['approver_id'])) {
            $where[] = ['approver_id', '=', $params['approver_id']];
        }
        
        if (!empty($params['start_date'])) {
            $where[] = ['report_date', '>=', strtotime($params['start_date'])];
        }
        
        if (!empty($params['end_date'])) {
            $where[] = ['report_date', '<=', strtotime($params['end_date'] . ' 23:59:59')];
        }

        return $this->where($where)
            ->with(['admin', 'approver'])
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $params['limit'] ?? 15,
                'page' => $params['page'] ?? 1,
            ]);
    }

    /**
     * 获取我的工作报告
     * @param int $adminId 管理员ID
     * @param array $params 查询参数
     * @return \think\Paginator
     */
    public function getMyReports($adminId, $params = [])
    {
        $where = [['admin_id', '=', $adminId]];
        
        if (!empty($params['report_type'])) {
            $where[] = ['report_type', '=', $params['report_type']];
        }
        
        if (isset($params['status']) && $params['status'] !== '') {
            $where[] = ['status', '=', $params['status']];
        }

        return $this->where($where)
            ->with(['admin', 'approver'])
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $params['limit'] ?? 15,
                'page' => $params['page'] ?? 1,
            ]);
    }

    /**
     * 获取待审核报告
     * @param int $approverId 审核人ID
     * @param array $params 查询参数
     * @return \think\Paginator
     */
    public function getPendingReports($approverId, $params = [])
    {
        $where = [
            ['approver_id', '=', $approverId],
            ['status', '=', 2] // 待审核
        ];
        
        if (!empty($params['report_type'])) {
            $where[] = ['report_type', '=', $params['report_type']];
        }

        return $this->where($where)
            ->with(['admin'])
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $params['limit'] ?? 15,
                'page' => $params['page'] ?? 1,
            ]);
    }

    /**
     * 提交工作报告
     * @param array $data 报告数据
     * @return bool|int
     */
    public function submitReport($data)
    {
        $data['report_date'] = isset($data['report_date']) ? strtotime($data['report_date']) : time();
        $data['status'] = 2; // 待审核
        $data['create_time'] = time();
        $data['update_time'] = time();
        
        return $this->insertGetId($data);
    }

    /**
     * 保存草稿
     * @param array $data 报告数据
     * @return bool|int
     */
    public function saveDraft($data)
    {
        $data['report_date'] = isset($data['report_date']) ? strtotime($data['report_date']) : time();
        $data['status'] = 1; // 草稿
        $data['create_time'] = time();
        $data['update_time'] = time();
        
        return $this->insertGetId($data);
    }

    /**
     * 更新工作报告
     * @param int $id 报告ID
     * @param array $data 更新数据
     * @return bool
     */
    public function updateReport($id, $data): bool
    {
        if (isset($data['report_date'])) {
            $data['report_date'] = strtotime($data['report_date']);
        }
        
        $data['update_time'] = time();
        
        $result = $this->where('id', $id)->update($data);
        return $result !== false;
    }

    /**
     * 审核工作报告
     * @param int $id 报告ID
     * @param int $status 审核状态
     * @param string $remark 审核意见
     * @param int $approverId 审核人ID
     * @return bool
     */
    public function approveReport($id, $status, $remark = '', $approverId = null): bool
    {
        $updateData = [
            'status' => $status,
            'approve_remark' => $remark,
            'approve_time' => time(),
            'update_time' => time(),
        ];
        
        if ($approverId) {
            $updateData['approver_id'] = $approverId;
        }
        
        $result = $this->where('id', $id)->update($updateData);
        return $result !== false;
    }

    /**
     * 获取工作报告详情
     * @param int $id 报告ID
     * @return array|null
     */
    public function getReportDetail($id)
    {
        return $this->with(['admin', 'approver'])->find($id);
    }

    /**
     * 获取某员工的工作报告统计
     * @param int $adminId 管理员ID
     * @param string $startDate 开始日期
     * @param string $endDate 结束日期
     * @return array
     */
    public function getReportStats($adminId, $startDate = null, $endDate = null)
    {
        $where = [['admin_id', '=', $adminId]];
        
        if ($startDate) {
            $where[] = ['report_date', '>=', strtotime($startDate)];
        }
        
        if ($endDate) {
            $where[] = ['report_date', '<=', strtotime($endDate . ' 23:59:59')];
        }

        $stats = $this->where($where)
            ->field('report_type, status, COUNT(*) as count')
            ->group('report_type, status')
            ->select()
            ->toArray();

        $total = $this->where($where)->count();

        $typeStats = [];
        $statusStats = [];

        foreach ($stats as $stat) {
            if (!isset($typeStats[$stat['report_type']])) {
                $typeStats[$stat['report_type']] = 0;
            }
            $typeStats[$stat['report_type']] += $stat['count'];
            
            if (!isset($statusStats[$stat['status']])) {
                $statusStats[$stat['status']] = 0;
            }
            $statusStats[$stat['status']] += $stat['count'];
        }

        return [
            'total' => $total,
            'type_stats' => $typeStats,
            'status_stats' => $statusStats,
        ];
    }

    /**
     * 删除工作报告
     * @param int|array $ids 报告ID
     * @return bool
     */
    public function deleteReport($ids): bool
    {
        if (is_array($ids)) {
            $result = $this->where('id', 'in', $ids)->delete();
        } else {
            $result = $this->where('id', $ids)->delete();
        }
        return $result !== false;
    }

    /**
     * 搜索器：按提交人ID搜索
     * @param \think\db\Query $query
     * @param int $value
     */
    public function searchAdminIdAttr($query, $value)
    {
        $query->where('admin_id', $value);
    }

    /**
     * 搜索器：按报告类型搜索
     * @param \think\db\Query $query
     * @param int $value
     */
    public function searchReportTypeAttr($query, $value)
    {
        $query->where('report_type', $value);
    }

    /**
     * 搜索器：按状态搜索
     * @param \think\db\Query $query
     * @param int $value
     */
    public function searchStatusAttr($query, $value)
    {
        $query->where('status', $value);
    }

    /**
     * 搜索器：按审核人ID搜索
     * @param \think\db\Query $query
     * @param int $value
     */
    public function searchApproverIdAttr($query, $value)
    {
        $query->where('approver_id', $value);
    }

    /**
     * 搜索器：按报告日期范围搜索
     * @param \think\db\Query $query
     * @param array $value
     */
    public function searchReportDateRangeAttr($query, $value)
    {
        if (is_array($value) && count($value) === 2) {
            $startTime = strtotime($value[0]);
            $endTime = strtotime($value[1] . ' 23:59:59');
            $query->whereBetween('report_date', [$startTime, $endTime]);
        }
    }

    /**
     * 搜索器：按标题搜索
     * @param \think\db\Query $query
     * @param string $value
     */
    public function searchTitleAttr($query, $value)
    {
        $query->where('title', 'like', '%' . $value . '%');
    }

    /**
     * 搜索器：按内容搜索
     * @param \think\db\Query $query
     * @param string $value
     */
    public function searchContentAttr($query, $value)
    {
        $query->where('content', 'like', '%' . $value . '%');
    }
}